<?php


namespace PKApp\Member;

use PKApp\Member\Classes\TraitMember;
use PKCommon\Controller\AdminSetController;
use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\MatchHelper;
use PKFrame\DataHandler\Numbers;

class AdminSetUserDetail extends AdminSetController
{

    use TraitMember;

    public function Main()
    {
        if (!request()->has('id', 'get')) {
            $modelId = request()->get('modelId');
            Numbers::IsId($modelId) ?: $this->noticeByPage('Model_IdEmpty', 'Model');
            $this->assign([
                'modelId' => $modelId,
                'id' => 0,
            ]);
        } else {
            $this->assign([
                'id' => request()->get('id'),
            ]);
        }
        $this->fetch('set_user_detail');
    }

    public function ApiByCreate()
    {
        $post = $this->model();
        $entity = $this->serviceByUser()->GetEntity(['userName' => $post['userName']]);
        !Arrays::Is($entity) ?: $this->noticeByJson('Exists_userName');
        $post['createTime'] = TIMESTAMP;
        $this->serviceByUser()->Add($post);
        $this->inputSuccess();
    }

    public function ApiByChange()
    {
        $post = $this->model();
        $id = request()->post('id');
        Numbers::IsId($id) ?: $this->noticeByJson('Empty_userId');
        $entity = $this->serviceByUser()->GetEntity(['userName' => $post['userName'], ['id', '!=', $id]]);
        !Arrays::Is($entity) ?: $this->noticeByJson('Exists_userName');
        $this->serviceByUser()->UpdateById($id, $post);
        $this->inputSuccess();
    }

    public function ApiByDel()
    {
    }

    protected function model(): array
    {
        $post = $this->checkModel(['userName', 'modelId', 'groupId', 'email', 'mobile']);
        $post['userName'] = $this->checkPostFieldIsEmpty('userName', 'UserName_Empty');
        MatchHelper::MatchFormat('letter_num', $post['userName'], 'Err_userName');
        // 超级管理员为唯一
        if ($post['id'] == 1) {
            $post['groupId'] = 1;
        } else {
            Numbers::IsId($post['groupId']) ?: $this->noticeByJson('Group_IdEmpty');
            if ($post['groupId'] == 1) {
                $entity = $this->serviceByUser()->CheckAndGetUserInfo(array('groupId' => $post['groupId']));
                !Arrays::Is($entity) ?: $this->noticeByJson('User_Group_AdministratorExists');
            }
        }
        Numbers::IsId($post['modelId']) ?: $this->noticeByPage('Model_IdEmpty', 'Model');
        $post['mobile'] = Numbers::To($post['mobile']);
        return $post;
    }
}